



//
//  NEnterpriseSearchVC.m
//  nncloud
//
//  Created by macfai on 2018/12/25.
//  Copyright © 2018 macfai. All rights reserved.
//
#import "PickerView.h"
#import "NEnterpriseSearchVC.h"
#import "NMineCell.h"
#import "NQiyeSumViewController.h"
#import "NEntPriseSearchResultVC.h"
#import "NRegisterTypeModel.h"
@interface NEnterpriseSearchVC()<UITableViewDelegate,UITableViewDataSource,STPickerSingleDelegate,UITextFieldDelegate,PickerViewResultDelegate>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)NSMutableArray *industryDataArray;

@property(nonatomic,strong)NSArray *titleArray;

@property(nonatomic,strong)NSArray *pickerArray;
@property(nonatomic,strong)NSMutableArray *areaArray;
@property(nonatomic,strong)NSMutableArray *unitPropertyArray;

@property(nonatomic,strong)NSMutableArray *regDataArray;

@property (nonatomic,assign)NSInteger index;

@property (nonatomic,strong)STPickerSingle *picker;

///行业
@property (nonatomic,copy)NSString *industry;
@property (nonatomic,copy)NSString *region;
@property (nonatomic,copy)NSString *markType;
@property (nonatomic,copy)NSString *jobNature;

///企业名称
@property (nonatomic,copy)NSString *entName;

@end

@implementation NEnterpriseSearchVC

#define cellIdentifier @"mineid"
#define SectionHeaderHeight  10.f

-(UITableView *)tableView{
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0 , 0, ScreenWidth , ScreenHeight - 64) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 60.f;
        _tableView.backgroundColor = kBackgroundColor;
        [_tableView registerNib:[UINib nibWithNibName:@"NMineCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
        _tableView.showsVerticalScrollIndicator = NO;
        //        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}

//
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    
    ///装载城市数据
    self.dataArray = [NSMutableArray array];
    self.industryDataArray = [NSMutableArray array];
    self.areaArray = [NSMutableArray array];
    self.unitPropertyArray = [NSMutableArray array];
    self.regDataArray = [NSMutableArray array];
    self.index = 0;
    [self.navigationItem setItemWithTitle:@"企业搜索" textColor:kNavigationTitleColor fontSize:18 itemType:center];
    self.titleArray = @[@"企业名称",@"所属行业",@"所属区域",@"工商注册类型",@"单位性质",];
    [self.view addSubview:self.tableView];
    [self addFooter];
    [self loadData];
    // Do any additional setup after loading the view.
}

//加载区域/注册类型/等等数据
- (void)loadData{
    ///所在区域
    [NNetworkClient getRequestWithBaseUrl:kDistrictUrl setParameters:nil success:^(id responseObject) {
//        YYLog(@"%@",responseObject);
        if ([responseObject[@"code"] integerValue]==0) {
            NSArray *array = responseObject[@"page"];
            for (NSDictionary *dic in array) {
                NSString *area = dic[@"districtName"];
                [self.areaArray addObject:area];
            }
        }
    } fail:^(NSError *error) {
        YYLog(@"%@",error);
    } delegater:nil];
    
    ///单位性质
    [NNetworkClient getRequestWithBaseUrl:kJobPropertyUrl setParameters:nil success:^(id responseObject) {
//        YYLog(@"%@",responseObject);
        if ([responseObject[@"code"] integerValue]==0) {
            NSArray *array = responseObject[@"page"];
            for (NSDictionary *dic in array) {
                NSString *area = dic[@"natureName"];
                [self.unitPropertyArray addObject:area];
            }
        }
    } fail:^(NSError *error) {
        YYLog(@"%@",error);
    } delegater:nil];

    ///工商注册
    [NNetworkClient getRequestWithBaseUrl:kRegistrTypeUrl setParameters:nil success:^(id responseObject) {
//        YYLog(@"工商注册:%@",responseObject);
        NSArray *array = responseObject[@"page"];
        ///方法1：正常for 循环  双重遍历
        ///借鉴省市picker思路
        for (int i=0; i<array.count; i++) {
            
            NRegisterTypeModel *model = [NRegisterTypeModel new];
            NSDictionary *dict = array[i];
            model.province = dict.allValues[0];
//            YYLog(@"相当于省：%@",model.province);
            model.list = [dict objectForKey:@"list"];
            NSMutableArray *tempArray = [NSMutableArray array];
            for (int i=0; i<model.list.count; i++) {
            NSDictionary *subDict = model.list[i];
            NSString *city = subDict.allValues[0];
            [tempArray addObject:city];
            }
            model.cities = [tempArray copy];
//            YYLog(@"省下的市：%@",model.cities);
            [self.dataArray addObject:model];
        }
        ///方法2：快速遍历循环 双重遍历
//        for (NSDictionary *dict in array) {
//            NRegisterTypeModel *model = [NRegisterTypeModel mj_objectWithKeyValues:dict];
//            NSMutableArray *tempArray = [NSMutableArray array];
//            for (NSDictionary *subDict in model.list) {
//                NRegisterTypeModel *sumbModel = [NRegisterTypeModel mj_objectWithKeyValues:subDict];
//                [tempArray addObject:sumbModel];
//            }
//            model.list = [tempArray copy];
//            YYLog(@"嵌套:%@",model.list)
//            [self.dataArray addObject:model];
//        }
        
    } fail:^(NSError *error) {
        YYLog(@"%@",error);
    } delegater:nil];
    
    ///行业分类
    [NNetworkClient getRequestWithBaseUrl:kIndustryTypeUrl setParameters:nil success:^(id responseObject) {
        YYLog(@"行业分类:%@",responseObject);
         NSArray *array = responseObject[@"page"];
        for (int i=0; i<array.count; i++) {
            NRegisterTypeModel *model = [NRegisterTypeModel new];
            NSDictionary *dict = array[i];
            model.province = dict.allValues[0];
            model.list = [dict objectForKey:@"list"];
            NSMutableArray *tempArray = [NSMutableArray array];
            for (int i=0; i<model.list.count; i++) {
                NSDictionary *subDict = model.list[i];
                NSString *city = [subDict objectForKey:@"industryInfoName"];
                [tempArray addObject:city];
            }
            model.cities = [tempArray copy];
            [self.industryDataArray addObject:model];
        }
    } fail:^(NSError *error) {
        YYLog(@"%@",error);
    } delegater:nil];
}
-(void)addFooter {
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 100.f)];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 20, 300, 50);
    btn.centerX = footer.centerX;
    btn.backgroundColor = ThemeBlue;
    btn.layer.cornerRadius = 5.f;
    btn.layer.masksToBounds = YES;
    [btn setTitle:@"确认搜索" forState:UIControlStateNormal];
    [btn addTarget: self action:@selector(tapAction:) forControlEvents:UIControlEventTouchUpInside];
    [footer addSubview:btn];
    self.tableView.tableFooterView = footer;
}
#pragma mark - 确认搜索
//确认搜索
- (void)tapAction:(UIButton *)btn{
    //跳转搜索结果页面
    NSDictionary *dct = @{@"enterpriseName":self.entName?:@"",@"enterpriseIndustry":self.industry?:@"",@"enterpriseRegion":self.region?:@"",@"enterpriseBusinessType":self.markType?:@"",@"enterpriseType":self.jobNature?:@""};
    NEntPriseSearchResultVC *result = [NEntPriseSearchResultVC new];
    result.dict = dct;
    [self.navigationController pushViewController:result animated:YES];
//    if (self.presentingViewController) {
//        WeakStament(ws);
//        [self dismissViewControllerAnimated:YES completion:^{
//            if (ws.parablock) {
//                ws.parablock(dct);
//            }
//        }];
//    } else {
//        //
////        [AFToast showText:@"接口调试中"];
//        NQiyeSumViewController *sum = [NQiyeSumViewController new];
//        sum.flag = @"search";
//        [self.navigationController pushViewController:sum animated:YES];
//    }
//    self.navigationController pushViewController:<#(nonnull UIViewController *)#> animated:<#(BOOL)#>
}

#pragma mark - datasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return  self.titleArray.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NMineCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    
    cell.nameLabelLeftMargin.constant = 25.f;
    cell.nameLabel.text = self.titleArray[indexPath.section];
    cell.arrowImg.hidden = YES;
    cell.setLabel.hidden = false;
    cell.setLabel.text = @"请选择";
    
//    if (indexPath.section==0) {
//        cell.setLabel.hidden = YES;
//        cell.titleTextField.hidden = false;
//        cell.textFieldLeftMargin.constant = 105.f;
//        cell.titleTextField.placeholder = @"请输入企业名称";
//        cell.titleTextField.delegate = self;
//        cell.titleTextField.tag = 999;
//
//    }
    
    switch (indexPath.section) {
        case 0:
        {
            cell.setLabel.hidden = YES;
            cell.titleTextField.hidden = false;
            cell.textFieldLeftMargin.constant = 105.f;
            cell.titleTextField.placeholder = @"请输入企业名称";
            cell.titleTextField.delegate = self;
            cell.titleTextField.tag = 999;
        }
            break;
        case 1:
        {
            if (self.industry) {
                cell.setLabel.text = self.industry;
            }
        }
            break;
        case 2:
        {
            if (self.region) {
                cell.setLabel.text = self.region;
            }
        }
            break;
        case 3:
        {
            if (self.markType) {
                cell.setLabel.text = self.markType;
            }
        }
            break;
        case 4:
        {
            if (self.jobNature) {
                cell.setLabel.text = self.jobNature;
            }
        }
            break;
        default:
            break;
    }
    return cell;
}
#pragma mark  STPickerdelegate
-(void)pickerSingle:(STPickerSingle *)pickerSingle selectedTitle:(NSString *)selectedTitle selectIndex:(NSInteger)selectIndex{
    
    YYLog(@"%@",selectedTitle);
    switch (pickerSingle.tag) {
            
        case 501:
        {
            //
            self.industry = selectedTitle;
        }
            break;
        case 502:
        {
            self.region = selectedTitle;
        }
            break;
        case 503:
        {
            self.markType = selectedTitle;
        }
            break;
        case 504:
        {
            self.jobNature = selectedTitle;
        }
            break;
      
        default:
            break;
    }
    
    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:self.index];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
}


#pragma mark - section head
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return SectionHeaderHeight;//如果设置section的header高度，不设置footer高度，footer默认等于header高度
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, SectionHeaderHeight)];
    view.backgroundColor = kBackgroundColor;
    return view;
}

#pragma mark - section foot
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}


#pragma mark - delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section!=0) {
        self.index = indexPath.section;
        [self addPickerWithIndexPath: indexPath];
        [self.view endEditing:YES];
    }
}
///添加picker
- (void)addPickerWithIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==1||indexPath.section==3) {
        //工商注册类型
        PickerView *vi = [[PickerView alloc] init];
        if (indexPath.section==1) {
            vi.cityArray = self.industryDataArray;
        }else{
            vi.cityArray = self.dataArray;
        }
        vi.tag = 1000+indexPath.section;
        vi.delegate = self;
        vi.type = PickerViewTypeCity;
        [self.view addSubview:vi];
        
    }else{
        
        STPickerSingle *single = [[STPickerSingle alloc]init];
        [single setArrayData:[self getArrayWithIndexPath:indexPath]];
        single.tag = indexPath.section+500;
        [single setTitleUnit:@""];
        [single setDelegate:self];
        [single show];
    }
    
}

#pragma mark - 级联picker delegate
-(void)pickerView:(UIView *)pickerView result:(NSString *)string{
    
    NSArray *array = [string componentsSeparatedByString:@"-"];
    
    YYLog(@"%@",array);
    string = [array lastObject];
    
    if (pickerView.tag==1000+3) {
        YYLog(@"%@",string);
        self.markType = string;
        
    }else{
        
        self.industry = string;
        
    }
    
    ///两种刷新方式
    [self.tableView reloadData];
    
//    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:self.index];
//    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
}
///获取picker 数据源
- (NSMutableArray *)getArrayWithIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.section) {
        case 1:
        {
//            self.pickerArray =@[@"机械装备制造",@"电子信息",@"铝深加工",@"食品加工",@"生物制药",@"清洁能源",@"其他行业"];
        }
            break;
        case 2:
        {
            self.pickerArray = self.areaArray;
        }
            break;
        case 3:
        {
//            self.pickerArray = @[@"私营",@"国营",];
        }
            break;
        case 4:
        {
            
            self.pickerArray = self.unitPropertyArray;
        }
            break;
        
        default:
            break;
    }
    
    return (NSMutableArray *)self.pickerArray;
    
}

#pragma mark - textField delegate
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag==999) {
        self.entName = textField.text;
    }
    
}

@end
